<template>
  <div class="app-container inv-form-box">
    <el-row :gutter="20">
      <el-col :xs="24" :sm="6" :md="6" :lg="4" class="dict-module">
        <!-- 搜索 -->
        <el-input v-hasPermi="['system:form:query']" v-model="searchName" placeholder="请输入单据名称" clearable size="small"
          prefix-icon="el-icon-search" style="margin-bottom:10px" />
        <!-- 新增主类 -->
        <div class="add-class" style="margin-bottom: 10px;">
          <el-button type="primary" v-hasPermi="['system:form:add']" size="mini" @click="addParentSort" plain>新增单据
          </el-button>
        </div>
         <div class="height-tree3">
        <el-tree :data="formTree" :loading="treeLoading" node-key="formId" :props="defaultProps"
          :filter-node-method="filterNode" ref="tree" :highlight-current="isHeight" @node-click="nodeClick">
          <span class="custom-tree-node" slot-scope="{ node, data }" style="width: 100%" @mouseenter="mouseenter(data)"
            @mouseleave="mouseleave(data)">
            <div class="chang-mourse">
              <span>{{ data.formCode }}-{{ node.label }}</span>
              <span class="mou-r" v-if="isOperation">
                <el-link v-hasPermi="['system:form:add']" v-show="data.opShow" size="mini" type="primary"
                  icon="el-icon-plus" @click.stop="addSort(node)">
                </el-link>
                <el-link v-hasPermi="['system:form:edit']" v-show="data.opShow" size="mini" style="color: #67c23a;"
                  type="primary" icon="el-icon-edit" @click.stop="uplateSort(node)"></el-link>
                <el-link v-hasPermi="['system:form:remove']" v-show="data.opShow" size="mini" style="color: #f56c6c;"
                  type="primary" icon="el-icon-delete" @click.stop="removeTree(node)"></el-link>
              </span>
            </div>
          </span>
        </el-tree>
        </div>
      </el-col>

      <el-col :sm="12" :md="12" :lg="6" :xs="20" v-show="isFormStatus === true">
        <div class="sort-content" ref="treeForm">
          <!-- 表单区域 -->
          <el-form :model="subTreeform" :rules="rules" ref="form" label-width="108px" style="margin: 20px 22px 0 20px;"
            :disabled="butChange == 'seeStatus'">
            <el-form-item label="上级单据ID" prop="parentId" class="ma-lable" style="display: none;">
              <el-input v-model="subTreeform.parentId"></el-input>
            </el-form-item>
            <el-form-item label="上级单据" class="ma-lable superior-class" v-if="isParentId">
              <el-input v-model="parentName" disabled></el-input>
            </el-form-item>
            <el-form-item label="单据编码" prop="formCode" class="ma-lable">
              <el-input v-model="subTreeform.formCode"></el-input>
            </el-form-item>
            <el-form-item label="单据名称" prop="formName" class="ma-lable">
              <el-input v-model="subTreeform.formName"></el-input>
            </el-form-item>
            <div style="margin-top: 10px;">
              <el-form-item label="单据状态" class="ma-lable">
                <el-select v-model="subTreeform.status">
                  <el-option label="正常" value="0"></el-option>
                  <el-option label="停用" value="1"></el-option>
                </el-select>
              </el-form-item>
            </div>
          </el-form>
          <div class="handle-save">
            <el-button type="primary" v-hasPermi="['system:form:add']" v-if="butChange == 'addStatus' " icon="el-icon-edit"
              @click="submitFromTree('form',treeNode)">确定
            </el-button>
            <el-button type="success" v-hasPermi="['system:form:edit']" v-if="butChange == 'updateStatus' "
              icon="el-icon-edit" @click="submitFromTree('form',treeNode)">保存
            </el-button>
            <el-button icon="el-icon-refresh" @click="resetTree"
              v-if="butChange == 'addStatus' || butChange == 'updateStatus'">重置</el-button>
          </div>
        </div>
      </el-col>
      <el-col :span="20">


        <Configure :key="refreshKey" :formTree="formTree" :openStatus="openStatus" :formId="transferData.formId"
          v-if="isFormStatus===false" />
      </el-col>

    </el-row>


  </div>
</template>

<script>
  import {
    listForm,
    addForm,
    updateForm,
    delForm
  } from "@/api/system/config";
  import Configure from "./config.vue"
  import {
    getTreeData,
    getEcho,
    supParent,
    selectNode,
    getCurrentNode,
    setCurrentNode
  } from "./utils/form.js"

  export default {
    name: "Form",
    data() {
      var checkModule = (rule, value, callback) => {
        if (this.selectValue == null) {
          return callback(new Error(''));
        } else {
          callback();
        }
      };
      return {
        //树形遮罩
        treeLoading: true,
        // 树形搜索
        searchName: "",
        //是否显示单据树形表单
        isFormStatus: false,
        // 上级单据名称
        parentName: "",
        //父单据id
        parentId: "",
        //上级单据是否显示
        isParentId: false,
        //物料特性/小数位数/规格别名/规格合并只是新增主类时显示
        specialStatus: false,
        // 物料特性列表
        optionsIndividua: [],
        selectIndividua: "",
        //节点是否有高亮属性
        isHeight: false,
        //是否显示单据操作按钮
        isOperation: true,
        //element-ui表头样式
        activeName: 'basicinfo',
        //树形数据
        formTree: [],
        //树形节点
        treeNode: "",
        //绑定树形数据名称
        defaultProps: {
          children: 'children',
          label: 'formName',
        },
        // 基本信息表单数据
        subTreeform: {
          formCode: "", //编码
          formName: "", //名称
          status: "0", //状态
          formPath: "" //完整路径
        },
        //按钮切换新增/保存
        butChange: "addStatus",
        // 遮罩层
        loading: true,
        //选择单据回显信息
        value: [],
        transferData: {
        formId:null
        },
        //单据选择配置
        classProps: {
          children: "children",
          label: "formName",
          value: "formCode",
          checkStrictly: true
        },
        refreshKey: "", //组件刷新
        openStatus: "treePage", //打开方式
        // 表单校验
        rules: {
          formName: [{
            required: true,
            trigger: 'blur'
          }],
          formCode: [{
            required: true,
            trigger: 'blur'
          }],

        }
      };
    },
    created() {
      //初始化单据数据
      this.getTreeList();
    },
    methods: {
      //获取单据数据
      getTreeList() {
        this.treeLoading = true;
        listForm().then(res => {
          this.formTree = getTreeData(res.data); //当children为0时，赋值undefined
          this.treeLoading = false;
        });
      },

      //添加主单据
      addParentSort() {
        this.resetTree() //重置表单内容
        this.isParentId = false; //父类名称为隐藏
        this.parentId = 0; //父类Id为0，代表添加主单据
        this.butChange = 'addStatus'; //按钮状态为添加
        this.isFormStatus = true;
      },

      //单据树选中
      nodeClick() {
        this.isFormStatus = false;
        this.isHeight = false;
        this.subTreeform = Object.assign({}, arguments[0]);
        this.parentId = this.subTreeform.parentId; //保存parentId，用来不触发新增按钮form提交
        this.treeNode = arguments[1]; //节点赋值，用来确定添加位置
        this.transferData.formId = arguments[0].formId;
        // this.uplateAdd(arguments[0][1]) //修改新增公共方法
        if (arguments[0].parentId == 0) { //父类Id为0，代表添加主单据
          this.isParentId = false; //父类名称为隐藏
          this.specialStatus = true;
        } else {
          this.isParentId = true;
        }
        this.butChange = 'seeStatus';
        this.refreshKey = Math.random()
      },

      // 从查看切换修改按钮
      handleUpdateTree() {
        this.butChange = 'updateStatus';
      },

      //添加子单据
      addSort(node) {
        this.isFormStatus = true;
        this.resetTree() //重置表单内容
        this.butChange = 'addStatus'; //按钮状态为添加
        this.uplateAdd(node); //修改新增公共方法
        this.isParentId = true; //父类名称为显示
        this.parentId = node.data.formId; //保存parentId，用来不刷新时表单提交
        this.treeNode = node; //节点赋值，用来确定添加位置
        this.viewEcho(node.data.formId);
      },

      //修改单据
      uplateSort(node) {
        this.butChange = 'updateStatus'; //按钮状态为保存
        this.isFormStatus = true;
        this.uplateAdd(node) //修改新增公共方法
        this.subTreeform = Object.assign({}, node.data); //拷贝表单内容，避免影响数据
        this.parentId = this.subTreeform.parentId; //保存parentId，用来不触发新增按钮form提交
        this.treeNode = node; //节点赋值，用来确定添加位置
        if (node.data.parentId == 0) { //父类Id为0，代表添加主单据
          this.isParentId = false; //父类名称为隐藏
        } else {
          this.isParentId = true;
        }
        // console.log(node.data.formId)
        // this.viewEcho(node.data.formId);
      },

      // 修改单据新增单据公共方法
      uplateAdd(node) {
        this.$refs.form.resetFields(); //清除表单验证
        // 上级单据高亮
        this.isHeight = true;
        const getNode = [];
        getCurrentNode(node, getNode).then(currentNode => {
          setCurrentNode(this.$refs.tree.root, currentNode)
        })
        // 获取上级单据名称
        const name = [];
        const getParentName = supParent(node, name).reverse(); //获取上级单据名称
        const parentName = getParentName.join(" / "); //拼接上级单据名称
        if (node.data.parentId == 0) {
          this.parentName = node.data.formName; //主类上级单据为自身
        } else if (this.butChange == 'addStatus') {
          this.parentName = parentName + " / " + node.data.formName //子类上级单据最终结果
        } else {
          this.parentName = parentName;
        }
      },

      // 单据回显
      viewEcho(id) {
        return new Promise((resolve, reject) => {
          let parentArr = [], //用于储存父类单据信息
            childrenArr = []; ////用于储存子类单据信息
          getEcho(id, this.formTree, parentArr, childrenArr).then((res) => {
            setTimeout(() => {
              let success = [];
              for (let i = 0; i < res.length; i++) {
                if (success.indexOf(res[i]) === -1) {
                  success.push(res[i])
                }
              }
              let getNode = JSON.parse(JSON.stringify(success)) //拷贝vuex信息，避免影响源数据
              getNode.forEach(v => {
                if (v.ancestors.indexOf(",") > -1) { //是否是子单据
                  v.ancestors = v.ancestors.split(",").length; //拼接数组长度，用于排序
                } else {
                  v.ancestors = 1;
                }
              })
              getNode.sort((a, b) => { //排序得到正常的单据顺序，用于得到form
                return a.ancestors - b.ancestors
              })
              let getCode = [];
              getNode.forEach(code => {
                getCode.push(code.formCode);
              })
              if (this.butChange == "addStatus") {
                getCode = getCode.join(""); //转换成字符串，用于传值后台
                this.transferData.formPath = getCode;
                console.log(this.transferData.formPath)
                resolve(this.transferData.formPath)
              } else if (this.butChange == "updateStatus") {
                if (getCode.length > 1) {
                  getCode.pop();
                  getCode = getCode.join(""); //转换成字符串，用于传值后台
                  this.transferData.formPath = getCode;
                  console.log(this.transferData.formPath)
                  resolve(this.transferData.formPath)
                }
              }
            }, 0)
          });

        })

      },

      //鼠标进入事件
      mouseenter(data) {
        this.$set(data, "opShow", true);
      },
      //鼠标离开事件
      mouseleave(data) {
        this.$set(data, "opShow", false);
      },
      // 树形筛选
      filterNode(value, data) {
        if (!value) return true;
        return data.formName.indexOf(value) !== -1;
      },
      //提交表单
      submitFromTree(form, node) {
        this.$refs[form].validate((valid) => {
          if (valid) {
            this.subTreeform.parentId = this.parentId; //赋值parentId，用来不刷新时表单提交
            if (this.subTreeform.parentId == 0) {
              this.subTreeform.formPath = this.subTreeform.formCode
            } else {
              this.subTreeform.formPath = this.transferData.formPath + this.subTreeform.formCode
            }
            if (this.butChange == "addStatus") { //触发新增提交
              console.log(this.subTreeform)
              addForm(this.subTreeform).then(res => {
                if (res.code == 200) {
                  this.msgSuccess("新增成功");
                  console.log(res)
                  console.log(this.subTreeform.parentId)
                  if (this.subTreeform.parentId === 0) {
                    this.formTree.push(res.data);
                  } else {
                    node.expand();
                    this.$refs.tree.append(res.data, node) //不刷新更新节点数据
                  }
                  this.resetTree(); //重置表单
                }

              }).catch(err => {
                this.msgError("新增失败");
              })
            } else {
              this.subTreeform.parentId = this.parentId; //赋值parentId，用来不刷新时表单提交
              if (this.subTreeform.parentId == 0) {
                this.subTreeform.formPath = this.subTreeform.formCode;
                updateForm(this.subTreeform).then(res => { //触发保存提交
                  if (res.code == 200) {
                    this.msgSuccess("保存成功");
                    this.subTreeform.version = res.data.version; //保存version，用来不刷新修改
                    node.data.formName = this.subTreeform.formName;
                    node.data.formCode = this.subTreeform.formCode;
                    node.data.status = this.subTreeform.status;
                    node.data.formPath = this.subTreeform.formPath;
                    node.data.version = res.data.version;
                  }

                }).catch(err => {
                  this.msgError("保存失败");
                })
              } else {
                this.viewEcho(this.subTreeform.formId).then((res) => {
                  this.subTreeform.formPath = res + this.subTreeform.formCode;
                  updateForm(this.subTreeform).then(res => { //触发保存提交
                    if (res.code == 200) {
                      this.msgSuccess("保存成功");
                      this.subTreeform.version = res.data.version; //保存version，用来不刷新修改
                      node.data.formName = this.subTreeform.formName;
                      node.data.formCode = this.subTreeform.formCode;
                      node.data.status = this.subTreeform.status;
                      node.data.formPath = this.subTreeform.formPath;
                      node.data.version = res.data.version;
                    }

                  }).catch(err => {
                    this.msgError("保存失败");
                  })
                })
              }

            }
          }
        });
      },

      //移除单据
      removeTree(node) {
        this.$confirm('确认删除', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delForm(node.data.formId);
        }).then((res) => {
          if (res.code == 200) {
            this.msgSuccess("删除成功");
            this.resetTree(); //重置表单
            this.isHeight = false;
            this.isParentId = false; //父类名称为隐藏
            this.parentId = 0; //父类Id为0，代表添加主单据
            this.butChange = 'addStatus'; //按钮状态为添加
            this.$refs.tree.remove(node) //移除节点
          }
        })
      },

      // 表单重置
      resetTree() {
        this.subTreeform.formName = "";
        this.subTreeform.formCode = "";
        this.subTreeform.status = "0";
      },
      // 树形筛选
      filterNode(value, data) {
        if (!value) return true;
        return data.formName.indexOf(value) !== -1;
      },

      //解决级联选择器回显高亮异常问题
      resetSelector() {
        if (this.$refs.classTree) {
          this.$refs.classTree.$refs.panel.activePath = [];
          this.$refs.classTree.$refs.panel.calculateCheckedNodePaths();
        }
      },
    },
    components: {
      Configure
    },
    watch: {
      searchName: {
        handler(newData) {
          this.$refs.tree.filter(newData);
        },
        deep: true
      }
    }
  };
</script>
<style lang="scss">
  .dick-select {
    input {
      color: #1890FF !important;
    }
  }

  .inv-form-dialog {
    .cas-input input {
      color: #1890FF !important;
    }

  }

  .inv-form-box {
    .el-tree--highlight-current .el-tree-node.is-current>.el-tree-node__content {
      background: none !important;
      color: #1890FF !important;
    }
    .height-tree3 {
      height: calc(100vh - 230px);
      overflow: auto;
    }
    .custom-tree-node {
      font-size: 14px;

      a {
        margin-left: 10px;

        &:hover i {
          font-weight: 700;

        }
      }

      .el-link.is-underline:hover:after {
        border: none !important;

      }
    }

    .chang-mourse {
      display: flex;
      justify-content: space-between;

      .mou-r {
        margin-right: 10px;
      }
    }

    .superior-class .el-input.is-disabled .el-input__inner {
      color: #1890FF !important;
    }

    .sort-content {
      border: 1px solid #ebebeb;
      padding: 10px 12px 10px 10px;
      border-radius: 5px;

      .el-tabs--border-card {
        box-shadow: inherit;
      }

      .el-form-item__label {
        font-weight: normal !important;
      }

      .handle-save {
        margin-top: 20px;
        margin-bottom: 20px;
        margin-right: 22px;
        text-align: right;

        .el-button--medium {
          padding: 8px;
          font-size: 13px;
        }

        .el-button--info {
          background: #ccc;
        }
      }

      .el-input.is-disabled .el-input__inner {
        color: #333;
      }
    }

  }
</style>
